package com.weiiew.backend.controller;

import com.weiiew.backend.entity.config.MouseClickConfig;
import com.weiiew.backend.executor.MouseClickExecutor;
import com.weiiew.backend.utils.ApiResponse;
import com.weiiew.backend.utils.listener.HotkeyListenerManager;
import com.weiiew.backend.utils.listener.MouseSitListener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/mouse")
public class MouseClickController {
    private final MouseClickExecutor mouseClickExecutor;
    private final HotkeyListenerManager manager;
    private final MouseSitListener mouseSitListener;
    private final SimpMessagingTemplate messagingTemplate;
    private MouseClickConfig config = new MouseClickConfig(); // 用于存储前端的鼠标配置

    @RequestMapping("/bind")
    public ApiResponse bindPageHotkeys() {
        // 注册开始快捷键（从配置中心读取）
        manager.registerHotkey("mouse.toggle",
                () -> mouseClickExecutor.startStopToggle(this.config));
        return ApiResponse.ok("快捷键绑定成功");
    }

    @RequestMapping("/unbind")
    public ApiResponse unbindPageHotkeys() {
        manager.unregisterPageHotkeys("mouse");
        return ApiResponse.ok("快捷键解绑成功");
    }


    // 新增：获取完整配置
    @GetMapping("/config")
    public ApiResponse getConfig() {
        System.out.println(this.config);
        return ApiResponse.ok().append("config", config);
    }

    // 新增：更新完整配置
    @PostMapping("/config")
    public ApiResponse updateConfig(@RequestBody MouseClickConfig newConfig) {
        this.config = newConfig;
        log.info("更新完整配置：{}", newConfig);
        return ApiResponse.ok("配置更新成功").append("config", config);
    }

    @PostMapping("/toggle")
    public ApiResponse toggleMouseClick() {
        mouseClickExecutor.startStopToggle(this.config);
        return ApiResponse.ok("成功切换执行器");
    }

    @PostMapping("/listener/mouse")
    public ApiResponse listenerMouseClick() {
        mouseSitListener.startMouseSitListener((x, y) -> {
            messagingTemplate.convertAndSend("/topic/mouse-move",
                    String.format("{\"x\": %d, \"y\": %d}", x, y));
            config.getPosition().setX(x);
            config.getPosition().setY(y);
        });
        return ApiResponse.ok("成功启动监听");
    }
}